<template>
  <div>
    <el-form class="form" :model="formData" @submit.prevent="$emit('search')">
      <el-row :gutter="20" align="middle">
        <!-- 家庭选择框 -->
        <el-col :span="6">
          <el-form-item label="家庭">
            <el-select
              v-model="localFormData.familyId"
              placeholder="请选择家庭"
              clearable
              filterable
              default-first-option
              @change="$emit('update:formData',localFormData)"
            >
              <el-option
                v-for="f in familyList"
                :key="f.id"
                :label="f.name"
                :value="f.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 日期范围选择器 -->
        <el-col :span="8">
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledFutureDate"
              @change="handleDateChange"
            />
          </el-form-item>
        </el-col>

        <!-- 快速日期选择 -->
        <el-col :span="4">
          <el-form-item label="快速选择">
            <el-select
              v-model="quickDate"
              placeholder="快速选择"
              @change="handleQuickDateChange"
            >
              <el-option label="今天" value="today"/>
              <el-option label="昨天" value="yesterday"/>
              <el-option label="最近7天" value="thisWeek"/>
              <el-option label="最近30天" value="thisMonth"/>
              <el-option label="上月" value="lastMonth"/>
              <el-option label="今年" value="thisYear"/>
              <el-option label="去年" value="lastYear"/>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 操作按钮组 -->
        <el-col :span="6" class="action-buttons">
          <el-button
            color="#3370ff"
            @click="handleSearch"
            :loading="loading"
            :icon="Search"
          >
            查询
          </el-button>

          <el-button
            type="success"
            @click="handleGenerateReport"
            :loading="generatingReport"
            :icon="Document"
          >
            生成报表
          </el-button>

          <el-dropdown @command="handleMoreActions" trigger="click">
            <el-button type="info" :icon="MoreFilled"/>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="refresh" :icon="Refresh">
                  刷新数据
                </el-dropdown-item>
                <el-dropdown-item command="advanced" :icon="Filter">
                  高级筛选
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-row>


    </el-form>

  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue';
import {Search, Document, MoreFilled, Refresh, Filter,} from '@element-plus/icons-vue';
import {ElMessage} from "element-plus";
import type {Family} from "@/api/detail/type.ts";
import dayjs from 'dayjs';

import {getAllFamily} from "@/api/family";
import type {FilterForm} from "@/api/statistics/type.ts";

const props = defineProps<{
  formData: FilterForm;
}>();

const localFormData = ref<FilterForm>({...props.formData});

const emit = defineEmits([
  'update:formData',
  'search',
  'refresh',
  'confirm'
]);

//加载状态
const loading = ref(false);
const dateRange = ref<string[]>([]);
const quickDate = ref('');
const generatingReport = ref(false);



// 家庭列表数据
const familyList = ref<Family[]>([]);

// 获取家庭数据
const getFamilies = async () => {
  try {
    const response = await getAllFamily();
    familyList.value = response.data.map(family => {
      return {
        id: family.id!,
        name: family.name!
      };
    });
  } catch (error) {
    console.error("获取家庭失败:", error);
  }
};



// 禁用未来日期
const disabledFutureDate = (time: Date) => {
  return time.getTime() > Date.now();
};


// 处理日期变化
const handleDateChange = (val: string[]) => {
  if (val && val.length === 2) {
    localFormData.value.startTime = val[0];
    localFormData.value.endTime = val[1];
  } else {
    localFormData.value.startTime = '';
    localFormData.value.endTime = '';
  }
  quickDate.value = '';
  emit('update:formData', localFormData.value);
};

// 处理快速日期选择
const handleQuickDateChange = (val: string) => {
  let start, end;
  const now = dayjs();

  switch (val) {
    case 'today':
      start = now.startOf('day');
      end = now.endOf('day');
      break;
    case 'yesterday':
      start = now.subtract(1, 'day').startOf('day');
      end = now.subtract(1, 'day').endOf('day');
      break;
    case 'thisWeek':
      start = now.subtract(7,'day')
      end = now;
      break;
    case 'thisMonth':
      start =  now.subtract(30,'day');
      end = now;
      break;
    case 'lastMonth':
      start = now.subtract(1, 'month').startOf('month');
      end = now.subtract(1, 'month').endOf('month');
      break;
    case 'thisYear':
      start = now.startOf('year');
      end = now.endOf('year');
      break;
    case 'lastYear':
      start = now.subtract(1, 'year').startOf('year');
      end = now.subtract(1, 'year').endOf('year');
      break;
    default:
      throw new Error('无效的日期选择');
  }

  dateRange.value = [start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD')];
  localFormData.value.startTime = dateRange.value[0];
  localFormData.value.endTime = dateRange.value[1];
  emit('update:formData', localFormData.value);
};

// 查询按钮点击
const handleSearch = () => {
  if (!localFormData.value.familyId) {
    ElMessage.warning("请先选择家庭");
    return;
  }
  emit('search');
};

// 生成报表
const handleGenerateReport = async () => {
  if (!localFormData.value.familyId) {
    ElMessage.warning("请先选择家庭");
    return;
  }

  generatingReport.value = true;
  try {
    // todo 生成报表
    ElMessage.success("报表生成成功");
  } catch (error) {
    ElMessage.error("报表生成失败");
    console.error("生成报表失败", error)
  } finally {
    generatingReport.value = false;
  }
};

// 更多操作
const handleMoreActions = (command: string) => {
  if (!localFormData.value.familyId) {
    ElMessage.warning("请先选择家庭");
    return;
  }

  switch (command) {
    case 'refresh':
      emit('refresh');
      break;
  }
};



onMounted(() => {
  getFamilies();
})
</script>

<style scoped lang="scss">
.form {
  width: 100%;
  padding: 16px;
  box-sizing: border-box;
  background-color: $base-card-bg-color;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  margin-bottom: 20px;

  .el-form-item {
    margin-bottom: 0;
  }

  :deep(.el-form-item__label) {
    color: var(--el-text-color-regular);
    font-weight: normal;
  }

  :deep(.el-select),
  :deep(.el-date-editor) {
    width: 100%;
  }

  .action-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;

    .el-button {
      display: inline-flex;
      align-items: center;
      gap: 6px;
    }
  }
}

@media (max-width: 1200px) {
  .form {
    .el-col {
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .action-buttons {
      justify-content: flex-start;
    }
  }
}
</style>
